#!/bin/bash

set -x

root=$(realpath $(cd $(dirname $0) && pwd)/../)
tar_path=$root/package/tar
jkzuc_debpath=$root/package/deb
venv_path=$root/package/.venv
pip_mirror="https://pypi.tuna.tsinghua.edu.cn/simple"

function download_pip_dep()
{
    # @param1 依赖下载目录
    local dep_dir="$1"

    if [ ! -d "$dep_dir" ]; then
        mkdir -p "$dep_dir"
    fi

    local pip="$venv_path/bin/python -m pip"
    local py="$venv_path/bin/python"

    echo "pip is $pip"
    echo "dest dir $dep_dir/aiohttp"

    # 版本参照tools/requirements.txt
    $pip download -d "$dep_dir" -r tools/requirements.txt -i $pip_mirror|| { echo "下载pip依赖失败, 退出"; exit 1; }
}

function prepare_venv()
{
    # 在package目录下新建一个.venv目录，
    # 然后将依赖的pip包先安装在这下面
    local dep_dir=$HOME/.scorpio_os_dep/amd64/depends
    local venv_pip="$venv_path/bin/pip"
    local error_stat=0

    rm -r $venv_path
    # pytho3python3如果使用pyc字节码表示时，python3.9和python3.10之间存在字节码的兼容性问题
    # 需要打包整个python解释环境
    /usr/bin/python3 -m venv --copies $venv_path

    $venv_pip install --no-index --force-reinstall -r $root/tools/requirements.txt -f $dep_dir || { echo "安装依赖失败，尝试重新下载依赖"; error_stat=1; }

    echo "error_stat:$error_stat"
    if [ "$error_stat" -eq "0" ]; then
        return
    fi

    download_pip_dep "$dep_dir"
    $venv_pip install --no-index --force-reinstall -r $root/tools/requirements.txt -f $dep_dir  || { echo "成功下载依赖, 安装失败, 退出"; exit=1; }
}

function build_src(){
    rm -rf $root/Release $root/build
    cmake -S $root -B$root/build -DCMAKE_BUILD_TYPE:STRING=Release -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE
    cmake --build $root/build --target install -- -j $(nproc)
}

# 
git clean -xdf $root/package

# 构建deb包准备venv依赖
prepare_venv

# 构建deb包
chmod 755 $jkzuc_debpath/DEBIAN/control
chmod 755 $jkzuc_debpath/DEBIAN/postinst
chmod 755 $jkzuc_debpath/DEBIAN/preinst
chmod 755 $jkzuc_debpath/DEBIAN/prerm

build_src
rm -f $root/package/*.deb

# 复制config
mkdir -p $jkzuc_debpath/usr/etc/jkzuc/python3
cp -f -R $root/package/.venv $jkzuc_debpath/usr/etc/jkzuc/python3

# 识别版本号和架构,并打包deb
verstr=$(awk '{print $1}' $root/VERSION)
dpkg -b $jkzuc_debpath $root/package/jkzuc-$verstr-$(date +"%Y%m%d%H%M").deb

# 构建压缩包
verstr2=$(echo $verstr | sed 's/\./_/g')
_path=$(realpath $root/package/JKZUC$verstr2)
rm -f $_path.tar.gz
cp -rf $root/package/tar $_path
cp $root/package/jkzuc-*.deb $_path/amd64
tar czf $_path.tar.gz -C $(dirname $_path) $(basename $_path)
rm -rf $_path
